/*******************************************
 * Copyright 2007 Aphrodite Framework for javaME .
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Public License v2.0
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 * Email : owner@aphroditeme.dev.java.net
 * Contributors:
 *     Kent Elton - initial API and implementation
 *******************************************/

package com.aphrodite.ui.widgets;

import javax.microedition.lcdui.Graphics;

/**
 * <p>
 * Glowing text Widget.The glow is based on the image array used.
 * </p>
 * The <code>setGlowColors(int[])</code> method can be used to set the glowing
 * colors.<br/> Four glow colors are specified by default.
 * 
 * @author kentelt
 * 
 */
public final class GlowingText extends TextEffect {

	/* fade colors */
	private int[] colors = new int[] { 0xff0000, 0x00ff00, 0x0000ff, 0xff00ff };

	private int currentColor;

	/* effect start time */
	private volatile long startTime = 0;

	public GlowingText(Theme theme, String text) {
		super(theme, 0, 0);
		this.text = text;
		this.currentColor = colors[0];
		updateModel();
		// startGlowing();
	}

	public void cleanUp() {
		super.cleanUp();
		colors = null;
	}

	protected void doAniTask() {
		long diff = System.currentTimeMillis() - startTime;
		int module = (int) (diff % effectInterval);
		int colorIndex = (int) (diff / effectInterval) % colors.length;
		currentColor = com.aphrodite.image.ColorUtil.middleColor(colors[(colorIndex + 1) % colors.length],
				colors[colorIndex], module, effectInterval);
	}

	public void render(Graphics g) {
		if (!isVisible)
			return;
		capture(g, width, height, false);
		g.setColor(currentColor);
		if (theme.bmFont != null) {
			theme.bmFont.drawString(g, text, 0, 0, 0);
		} else {
			g.setFont(theme.widgetFont);
			g.drawString(text, 0, 0, 0);
		}
		release(g, width, height, false);

	}

	/**
	 * Set the glowing color
	 * 
	 * @param rgb
	 * @throws NullPointerException
	 *             if the colors are null
	 */
	public void setGlowColors(int[] rgb) {
		if (rgb == null) {
			throw new NullPointerException();
		}
		this.colors = rgb;
	}

	protected void updateModel() {
		if (theme.bmFont != null) {
			width = theme.bmFont.stringWidth(text);
			height = theme.bmFont.getHeight();
		} else {
			width = theme.widgetFont.stringWidth(text);
			height = theme.widgetFont.getHeight();
		}
		sizeChanged(width, height);

	}

}
